from skimage import data
from matplotlib import pyplot as plt
import math
import numpy as np
import sys

image=data.coffee()
#image=data.imread('flower.jpg')
#定义RGB图像转换为HIS图像的函数
def rgb2hsi(r,g,b,hsi_image):
    
    
    hsi_image=np.zeros(image.shape,dtype='uint8')
    for ii in range(image.shape[0]):
        for jj in range(image.shape[1]):
            r,g,b=image[ii,jj,:]
            h,s,i=rgb2hsi(r,g,b)
#            hsi_image[ii,jj,:]=(h,s,i)     
            r=r/255
            g=g/255
            b=b/255
            num=0.5*((r-g)+(r-b))
            den=((r-g)*(r-g)+(r-b)*(g-b))**0.5
            #h(x,y)
            if b<=g:
                if den==0:
                    den=sys.float_info.min
                h=math.acos(num/den)
            elif b>g:
                if den==0:
                    den=sys.float_info.min
                h=(2*math.pi)-math.acos(num/den)
            #s(x,y)
            s=1-(3*min(r,g,b)/(r+g+b))
            #i(x,y)
            i=(r+g+b)/3
            
        #    hsi_image = rgb_image.copy()
        hsi_image[ii,jj,:] = (h,s*100,i*255)
#            hsi_image[:,:,1] = s*255
#            hsi_image[:,:,2] = i*255
    return  hsi_image


#定义HSI图像转换为RGB图像的函数
def hsi2rgb(h,s,i,rgb_image):
  
    rgb_image=np.zeros(image.shape,dtype='uint8')
    for ii in range(image.shape[0]):
        for jj in range(image.shape[1]):
            h,s,i=image[ii,jj,:]
            r,g,b=hsi2rgb(h,s,i)
#            rgb_image[ii,jj,:]=(r,g,b)
            if h>=0 and h<=2*np.pi/3:
                b=i*(1-s)
                r=i*(1+(s*math.cos(h)/math.cos((np.pi/3)-h)))
                g=3*i-(r+b)
            elif h>=2*np.pi/3 and h<=4*np.pi/3:
                h=h-(2*np.pi/3)
                r=i*(1-s)
                g=i*(1+(s*math.cos(h)/math.cos((np.pi)-h)))
                b=3*i-r-g
        #    elif h>=4*np.pi/3 and h<=2*np.pi:
            else:
                h=h-(4*np.pi/3)
                g=i*(1-s)
                b=i*(1+(s*math.cos(h)/math.cos((5*np.pi/3)-h)))
                r=3*i-g-b
                
            
        #    rgb_image = hsi_image.copy()
        rgb_image[ii,jj,:] =(r,g,b)
    
    return rgb_image


